<?php

namespace app\modules\weixin\controllers;

use app\common\services\ShortMessageServices;
use app\common\services\StaticServices;
use app\models\IntegralGood;
use app\models\IntegralRecord;
use app\models\Member;
use app\models\MemberIntegral;
use app\models\Recommend;
use app\models\User;
use app\modules\weixin\controllers\common\BaseController;
use Yii;
use yii\base\Exception;
use yii\web\Response;

class UserController extends BaseController {
  /**
   * 经纪人
   * @return array
   */
  public function actionAgent()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $session_user = Yii::$app->session->get('user_info');
      if (empty($session_user)) {
        throw new Exception('请先登录');
      }
      $recommend_count = Recommend::find()->where(['recommend_id' => $session_user['id'], 'recommend_type' => 6])->count();
      $no_recommend_commission = Recommend::find()->where(['recommend_id' => $session_user['id'], 'commission_status' => 1])->sum('recommend_commission');
      $data = [
          'recommend_count'         => $recommend_count,
          'no_recommend_commission' => $no_recommend_commission,
          'user_name'               => $session_user['user_name'],
      ];
      return ['code' => 200, 'data' => $data];
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 经纪人修改手机
   * @return array
   */
  public function actionChangePhone()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $new_phone = trim(Yii::$app->request->post('new_phone'));
      $confirm_phone = trim(Yii::$app->request->post('confirm_phone'));
      $code = trim(Yii::$app->request->post('code'));
      $session_user = Yii::$app->session->get('user_info');
      if (!preg_match("/^1[34578]{1}\d{9}$/", $new_phone) || !preg_match("/^1[34578]{1}\d{9}$/", $confirm_phone) || $new_phone != $confirm_phone) {
        throw new Exception('请填写正确的手机号码');
      }
      $short_msg = new ShortMessageServices();
      $check_code = $short_msg->CheckCode($code);
      if ($check_code['code'] != 200) {
        throw new Exception($check_code['msg']);
      }
      $user_info = User::find()->where(['id' => $session_user['id']])->one();
      if (!$user_info) {
        throw new Exception('数据有误');
      }
      $user_info->user_phone = $new_phone;
      $user_info->update_time = time();
      $user_info->save(0);
      $short_msg->UseCode($code);
      return ['code' => 200, 'msg' => '修改成功'];
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 获取修改手机验证码
   * @return array
   */
  public function actionGetCode()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $user_phone = trim(Yii::$app->request->post('user_phone'));
      $template = '您正在进行更换绑定手机号操作，验证码为{code}，5分钟内有效；如非本人操作，请忽略此短信。';
      StaticServices::getCode(mt_rand(100000, 999999), $template, $user_phone, 4);
      return ['code' => 200, 'msg' => '发送成功'];
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 经纪人排行
   * @return array
   */
  public function actionAgentRank()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $commission = User::find()->select('id,user_name,commission')->where(['in', 'user_role', [1, 4]])->orderBy(['commission' => SORT_DESC])->limit(10)->asArray()->all();
      $recommend_count = Recommend::find()->select('id,recommend_id,count(recommend_id) as recommend_count')->where(['recommend_type' => 6])->groupBy('recommend_id')->asArray()->all();
      foreach ($commission as &$item) {
        foreach ($recommend_count as $value) {
          if ($value['recommend_id'] == $item['id']) {
            $item['recommend_count'] = $value['recommend_count'];
          }
        }
      }
      return ['code' => 200, 'data' => $commission];
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 经纪人推荐用户
   * @return array
   */
  public function actionAgentInvitation()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $member_name = trim(Yii::$app->request->post('member_name'));
      $member_phone = trim(Yii::$app->request->post('member_phone'));
      $member_belong = intval(Yii::$app->request->post('member_belong'));
      $remark = trim(Yii::$app->request->post('remark'));
      $session_user = Yii::$app->session->get('user_info');
      if (!preg_match("/^(0|86|17951)?(1[356789])[0-9]{9}$/", $member_phone)) {
        throw new Exception('请填写正确的手机号码~~~~');
      }

      if (!in_array($member_belong, [1, 2])) {
        throw new Exception('请选择所属楼盘');
      }

      if ($session_user['user_name'] == $member_name && $session_user['user_phone'] == $member_phone) {
        throw new Exception('自己不能推荐自己');
      }
      $member_info = Member::find()->where(['member_phone' => $member_phone])->one();
      if ($member_info) {
        throw new Exception('此用户已经被推荐');
      }
      $default_pwd = strtolower(StaticServices::getRandChar(6));
      $member_arr = new Member();
      $member_arr->member_name = $member_name;
      $member_arr->member_phone = $member_phone;
      $member_arr->member_pwd = $default_pwd;
      $member_arr->recommend_id = $session_user['id'];
      $member_arr->member_belong = $member_belong;
      $member_arr->update_time = time();
      $member_arr->create_time = time();
      if ($member_arr->save(0)) {
        $recommend = new Recommend();
        $recommend->member_id = $member_arr->id;
        $recommend->member_name = $member_name;
        $recommend->recommend_id = $session_user['id'];
        $recommend->recommend_name = $session_user['user_name'];
        $recommend->recommend_source = 1;
        if ($remark) {
          $recommend->remark = $remark;
        }
        $recommend->update_time = time();
        $recommend->create_time = time();
        $recommend->save(0);
        return ['code' => 200, 'msg' => '推荐成功'];
      }
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 经纪人推荐用户列表
   * @return array
   */
  public function actionAgentMember()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $recommend_type = Yii::$app->request->post('recommend_type', 'valid');
      $session_user = Yii::$app->session->get('user_info');
      $p = intval(Yii::$app->request->post('p', 1));
      $recommend_info = Recommend::find()->where(['recommend_id' => $session_user['id']]);
      if ($recommend_type == 'new') {
        $recommend_info->andWhere(['recommend_type' => 8]);
      } elseif ($recommend_type == 'no_valid') {
        $recommend_info->andWhere(['recommend_type' => 7]);
      } else {
        $recommend_info->andWhere(['in', 'recommend_type', [1, 2, 3, 4, 5, 6, 9]]);
      }

      $page_size = 20;
      $total_count = $recommend_info->count();
      $total_page = ceil($total_count / $page_size);

      $list = $recommend_info->offset(($p - 1) * $page_size)->orderBy(['update_time' => SORT_DESC])->limit($page_size)->asArray()->all();
      $list['new_count'] = Recommend::getNewMemberCount($session_user['id']);
      $list['valid_count'] = Recommend::getValidCount($session_user['id']);
      $list['no_valid_count'] = Recommend::getNoValidCount($session_user['id']);
      $list['total_page'] = $total_page;
      return ['code' => 200, 'data' => $list];
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  public function actionAgentCommission()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $p = intval(Yii::$app->request->post('p', 1));
      $commission_type = Yii::$app->request->post('commission_type');
      $session_user = Yii::$app->session->get('user_info');
      $recommend_info = Recommend::find();

      if ($commission_type == 'over') {
        $recommend_info->where(['recommend_id' => $session_user['id'], 'commission_status' => 2]);
      } else {
        $recommend_info->where(['recommend_id' => $session_user['id'], 'commission_status' => 1]);
      }
      $page_size = 20;
      $total_count = $recommend_info->count();
      $total_page = ceil($total_count / $page_size);
      $no_over_commission = Recommend::noovercommission($session_user['id']);
      $over_commission = Recommend::overcommission($session_user['id']);
      $list = $recommend_info->offset(($p - 1) * $page_size)->orderBy(['update_time' => SORT_DESC])->limit($page_size)->asArray()->all();
      $list['total_page'] = $total_page;
      $list['no_over_commission'] = $no_over_commission;
      $list['over_commission'] = $over_commission;
      return ['code' => 200, 'data' => $list];
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 顾问
   * @return array
   */
  public function actionGu()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $session_user = Yii::$app->session->get('user_info');
      $recommend_info = Recommend::find()->where(['opertion_id' => $session_user['id']])->asArray()->all();
      return ['code' => 200, 'data' => $recommend_info];
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 置业经理接口
   * @return array
   */
  public function actionManager()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $p = intval(Yii::$app->request->post('p', 1));
      $session_user = Yii::$app->session->get('user_info');
      $user_info = User::find()->where(['id' => $session_user['id']])->one();
      $recommend_type = intval(Yii::$app->request->post('recommend_type', 8));
      if ($user_info->user_role == 2) {
        $recommend_info = Recommend::find()->joinWith('member')->where(['recommend_type' => $recommend_type, 'opertion_id' => 0]);
      } else {
        if ($recommend_type == 7) {
          $recommend_info = Recommend::find()->joinWith('member')->where(['opertion_id' => $user_info->id, 'recommend_type' => $recommend_type]);
        } else {
          $recommend_info = Recommend::find()->joinWith('member')->where(['opertion_id' => $user_info->id])->andWhere(['in', 'recommend_type', [1, 2, 3, 4, 5, 6, 9]]);
        }
      }
//      $commandQuery = clone $recommend_info;
//      echo $commandQuery->createCommand()->getRawSql();die;
      $page_size = 10;
      $total_count = $recommend_info->count();
      $total_page = ceil($total_count / $page_size);

      $list = $recommend_info->offset(($p - 1) * $page_size)->orderBy(['update_time' => SORT_DESC])->limit($page_size)->asArray()->all();

      $list['user_role'] = StaticServices::getUserRole()[$user_info['user_role']];
      $list['user_name'] = $user_info['user_name'];
      $list['total_page'] = $total_page;
      return ['code' => 200, 'data' => $list];
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 设置用户状态
   * @return array
   */
  public function actionSetMemberStatus()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $member_id = intval(Yii::$app->request->post('member_id'));
      $recommend_type = intval(Yii::$app->request->post('recommend_type'));
      $recommend_remark = trim(Yii::$app->request->post('remark'));
      if (!$member_id) {
        throw new Exception('参数有误');
      }
      $session_user = Yii::$app->session->get('user_info');
      $user_info = User::find()->select('id,user_role')->where(['id' => $session_user['id']])->one();

      if ($user_info->user_role == 2) {
        $recommend_info = Recommend::find()->where(['member_id' => $member_id])->one();
      } else {
        $recommend_info = Recommend::find()->where(['opertion_id' => $session_user['id'], 'member_id' => $member_id])->one();
      }
      if (!$recommend_info) {
        throw new Exception('数据有误');
      }
      $recommend_info->recommend_type = $recommend_type;
      if ($recommend_type == 7) {
        $recommend_info->remark = $recommend_remark;
      }
      $recommend_info->update_time = time();
      $recommend_info->save(0);
      return ['code' => 200, 'msg' => '修改成功'];
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 顾问跟进用户列表
   * @return array
   */
  public function actionGuMember()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $member_phone = trim(Yii::$app->request->get('member_phone'));
      $session_user = Yii::$app->session->get('user_info');
      if (mb_strlen($member_phone, 'utf-8') != 11 && !preg_match("/^1[34578]{1}\d{9}$/", $member_phone)) {
        throw new Exception('请填写正确的手机号码');
      }
      $member_info = Member::find()->where(['member_phone' => $member_phone])->one();
      if (!$member_info) {
        throw new Exception('用户数据有误');
      }
      if ($session_user['user_role'] == 2) {
        $recommend = Recommend::find()->where(['member_id' => $member_info->id])->asArray()->one();
      } else {
        $recommend = Recommend::find()->where(['opertion_id' => $session_user['id'], 'member_id' => $member_info->id])->asArray()->one();
      }
      $recommend['memner_phone'] = $member_info->member_phone;
      return ['code' => 200, 'data' => $recommend];
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 给与用户积分
   * @return array
   */
  public function actionGiveIntegral()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $member_id = intval(Yii::$app->request->post('member_id'));
      $integral = intval(Yii::$app->request->post('integral'));
      if (!$member_id) {
        throw new Exception('参数有误');
      }
      $member_info = Member::find()->where(['id' => $member_id, 'self_status' => 1])->one();
      if (!$member_info) {
        throw new Exception('此用户不存在');
      }
      $recommend_info = Recommend::find()->where(['member_id' => $member_id, 'recommend_type' => 7])->one();
      if ($recommend_info) {
        throw new Exception('此用户不是会员');
      }
      if (mb_strlen($integral, 'utf-8') < 1 || $integral < 1) {
        throw new Exception('赠送积分不正确');
      }
      $member_integral = new MemberIntegral();
      $member_integral->member_id = $member_id;
      $member_integral->integral = $integral;
      $member_integral->integral_source = 3;
      $member_integral->update_time = time();
      $member_integral->create_time = time();
      if ($member_integral->save(0)) {
        $member_info->member_integral += $integral;
        $member_info->update_time = time();
        $member_info->save(0);
        return ['code' => 200, 'msg' => '积分赠送完成'];
      }
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 兑换奖品
   * @return array
   */
  public function actionExchange()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      if (Yii::$app->request->isGet) {
        $check_code = strtolower(trim(Yii::$app->request->get('check_code')));
        if (mb_strlen($check_code, 'utf-8') < 6) {
          throw new Exception('参数有误');
        }
        $integral_good = IntegralRecord::find()->where(['check_code' => $check_code])->one();
        if (!$integral_good) {
          throw new Exception('数据有误');
        }
        if ($integral_good->record_status == 1) {
          throw new Exception('此商品已经兑换了,不能再次兑换');
        }
        $member_info = Member::find()->select('id,member_name')->where(['id' => $integral_good->member_id])->one();
        $good_info = IntegralGood::find()->select('id,good_name')->where(['id' => $integral_good->good_id])->one();
        if (!$member_info || !$good_info) {
          throw new Exception('数据有误');
        }
        $data = [
            'member_name'   => $member_info->member_name,
            'good_name'     => $good_info->good_name,
            'exchange_time' => $integral_good->create_time,
        ];
        return ['code' => 200, 'data' => $data];
      }

      if (Yii::$app->request->isPost) {
        $check_code = strtolower(trim(Yii::$app->request->post('check_code')));
        if (mb_strlen($check_code, 'utf-8') < 6) {
          throw new Exception('参数有误');
        }
        $integral_good = IntegralRecord::find()->where(['check_code' => $check_code])->one();
        if (!$integral_good) {
          throw new Exception('数据有误');
        }
        $integral_good->record_status = 1;
        $integral_good->update_time = time();
        $integral_good->save(0);
        return ['code' => 200, 'msg' => '兑换成功'];
      }
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 经理指派顾问
   * @return array
   */
  public function actionManagerAssign()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $user_name = trim(Yii::$app->request->post('user_name'));
      $user_id = intval(Yii::$app->request->post('user_id'));
      $member_id = intval(Yii::$app->request->post('member_id'));
      $user_info = User::find()->where(['user_name' => $user_name, 'id' => $user_id])->one();
      if (!$user_info) {
        throw new Exception('数据有误');
      }
      $recommend_info = Recommend::find()->where(['member_id' => $member_id])->one();
      if (!$recommend_info) {
        throw new Exception('用户数据有误');
      }
      $recommend_info->opertion_id = $user_id;
      $recommend_info->opertion_name = $user_info->user_name;
      $recommend_info->recommend_type = 9;
      $recommend_info->update_time = time();
      $recommend_info->save(0);
      return ['code' => 200, 'msg' => '指派成功'];
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 顾问列表
   * @return array
   */
  public function actionGuList()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $user_info = User::find()->select('id,user_name')->where(['user_role' => 3])->all();
      if (!$user_info) {
        throw new Exception('数据错误');
      }
      return ['code' => 200, 'data' => $user_info];
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }
}
